import json
from typing import Dict

from flask import Response


def success(data: object = None, msg: str = "保存成功") -> Dict[str, object]:
    wrap_data: Dict = {}
    if data:
        if not isinstance(data, Dict):
            wrap_data["res"] = data
        else:
            wrap_data = data
    return {
        "status": 0,
        "msg": msg,
        "data": wrap_data,
    }


def failure(msg: str = "", errors=None) -> Dict[str, object]:
    if errors is None:
        return {
            "status": 400,
            "msg": msg,
            "data": None,
        }
    else:
        return {
            "status": 400,
            "msg": msg,
            "errors": errors,
            "data": None,
        }


def validate_failure(msg: str = "", errors=None) -> Dict[str, object]:
    """
    status: 返回 0 表示校验成功，422 表示校验失败;
    errors: 返回 status 为 422 时，显示的校验失败信息;
    """
    if errors is None:
        return {
            "status": 422,
            "msg": msg,
            "data": None,
        }
    else:
        return {
            "status": 422,
            "msg": msg,
            "errors": errors,
            "data": None,
        }


def is_blank(obj: str) -> bool:
    return obj is None or obj.strip() == ''


def is_not_blank(obj: str) -> bool:
    return not (obj is None) and len(obj.strip()) > 0


def json_resp(json_obj: any):
    return Response(json.dumps(json_obj, ensure_ascii=False), mimetype="application/json")
